#include "../../../shared/dal/search_repo.hpp"
#include <chrono>
#include <gflags/gflags.h>
#include <memory>
#include <gtest/gtest.h>
#include <thread>

DEFINE_bool(run_mode, false, "程序的运行模式: false-调试 true-发布");
DEFINE_string(log_file, "", "发布模式下，用于指定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下，用于指定日志输出等级");

DEFINE_string(es_host, "http://127.0.0.1:9200/", "es服务器URL");

shared::dal::MessageSearchPtr esMessage;

TEST(TransmiteESTest, CreateIndex) 
{
    ASSERT_TRUE(esMessage->createIndex());
}

TEST(TransmiteESTest, AppendData) 
{
    ASSERT_TRUE(esMessage->appendData(
        "session-1", "msg-1", "uid-1", 1758146279, "this is a test message[1].")
    );
    ASSERT_TRUE(esMessage->appendData(
        "session-1", "msg-2", "uid-2", 1758246279, "this is a test message[2].")
    );
    ASSERT_TRUE(esMessage->appendData(
        "session-2", "msg-3", "uid-2", 1758346279, "this is a test message[3].")
    );
    ASSERT_TRUE(esMessage->appendData(
        "session-2", "msg-4", "uid-2", 1758446279, "this is a test message[4].")
    );
}

TEST(TransmiteESTest, Search) 
{
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    auto messages = esMessage->search("message", "session-1");
    ASSERT_EQ(messages.size(), 2);
    ASSERT_EQ(messages[0].messageId(), "msg-1");
    ASSERT_EQ(messages[0].sessionId(), "session-1");
    ASSERT_EQ(messages[0].userId(), "uid-1");
    ASSERT_EQ(boost::posix_time::to_time_t(messages[0].createTime()), 1758146279);
    ASSERT_EQ(messages[0].content(), "this is a test message[1].");

    ASSERT_EQ(messages[1].messageId(), "msg-2");
    ASSERT_EQ(messages[1].sessionId(), "session-1");
    ASSERT_EQ(messages[1].userId(), "uid-2");
    ASSERT_EQ(boost::posix_time::to_time_t(messages[1].createTime()), 1758246279);
    ASSERT_EQ(messages[1].content(), "this is a test message[2].");

    messages = esMessage->search("2", "session-1");
    ASSERT_EQ(messages.size(), 1);
    ASSERT_EQ(messages[0].messageId(), "msg-2");
    ASSERT_EQ(messages[0].sessionId(), "session-1");
    ASSERT_EQ(messages[0].userId(), "uid-2");
    ASSERT_EQ(boost::posix_time::to_time_t(messages[0].createTime()), 1758246279);
    ASSERT_EQ(messages[0].content(), "this is a test message[2].");
}

int main(int argc, char* argv[])
{
    testing::InitGoogleTest(&argc, argv);
    google::ParseCommandLineFlags(&argc, &argv, true);
    shared::init_logger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);

    auto esClient = shared::dal::ESClientFactory::create({FLAGS_es_host});

    esMessage = std::make_shared<shared::dal::MessageSearch>(esClient);

    return RUN_ALL_TESTS();
}